package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IFollowService followService;


    /**
     * 查询热点博客
     * @param current
     * @return
     */
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            queryBlogUser(blog);
            //查询是否点赞
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    /**
     * 根据id查询博客
     * @param id
     * @return
     */
    @Override
    public Result queryById(Long id) {
        Blog blog = getById(id);

        if (blog == null)
            return Result.fail("博客不存在喵！");

        //获取博主的用户信息
        queryBlogUser(blog);

        //查询是否点赞
        isBlogLiked(blog);

        return Result.ok(blog);
    }


    /**
     * 获取博客信息，并查询用户数据库，设置博主的头像、昵称
     * @param blog
     */
    private void queryBlogUser(Blog blog){
        //获取博主的用户信息
        Long userId = blog.getUserId(); //获取userId
        blog.setIcon(userService.getById(userId).getIcon());
        blog.setName(userService.getById(userId).getNickName());
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 点赞功能
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        //获取当前登录用户
        Long userId = UserHolder.getUser().getId();

        //判断当前用户是否点赞
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Double score = redisTemplate.opsForZSet().score(key, userId.toString());

        //未点赞，即Score为空
        if (score == null) {
            //数据库点赞数+1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if (isSuccess)  //若更新数据库成功
                //保存用户到redis
                redisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
        }
        //已点赞
        else {
            //数据库点赞数-1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if (isSuccess)
                //从redis中移除用户
                redisTemplate.opsForZSet().remove(key, userId.toString());
        }

        return Result.ok();
    }


    /**
     * 查询当前博客的点赞排行（前五）
     * @param id
     * @return
     */
    @Override
    public Result blogLikeRank(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Set<String> top5Id = redisTemplate.opsForZSet().range(key, 0, 4);
        List<UserDTO> userDTOList = top5Id.stream()
                .map(
                        //使用stream流，根据userId查询userDTO并封装为list
                        userId -> BeanUtil.copyProperties(userService.getById(Integer.parseInt(userId)), UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOList);
    }


    /**
     * 发布博客，保存至数据库&redis中
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSave = save(blog);

        if (!isSave)
            return Result.fail("保存博客失败！");

        //将博客发送给粉丝
        //获取粉丝id
        /*
        对应sql为：
            select * from tb_follow where follow_user_id = blog.getUserId()
        follow_user_id为当前用户关注的博主的id，我们只需要找到关注博主为当前发布者的所有用户，即当前博主的粉丝
         */
        Long bloggerId = blog.getUserId();  //博主id
        List<Follow> followUser = followService.query()
                .eq("follow_user_id", bloggerId)     //查找关注了该博主的粉丝
                .list();
        //通过粉丝id为key分别保存到对应redis中
        followUser.forEach(follow -> {
            Long userId = follow.getUserId();   //获取粉丝id
            String key = RedisConstants.BLOG_INBOX_KEY + userId;    //以粉丝id构建粉丝收件箱
            redisTemplate.opsForZSet()
                    .add(key, blog.getId().toString(), System.currentTimeMillis());   //以时间戳为score存入ZSet中
        });

        // 返回id
        return Result.ok(blog.getId());
    }


    /**
     * 关注推送页面的分页查询
     * @param lastId  上一次查询的最小时间戳，将作为本次查询的开始，即max
     * @param offSet  上一次查询的具有相同score的元素个数，作为此次查询开始的偏移量
     * @return
     */
    @Override
    public Result queryBlogWithFollow(Long lastId, Integer offSet) {
        //第一次时需由我们自行指定偏移量
        if (offSet == null)
            offSet = 0;

        String key = RedisConstants.BLOG_INBOX_KEY + UserHolder.getUser().getId();  //获取当前用户的收件箱key

        //基于请求参数进行反向滚动查询，查询当前用户收件箱所有的blog的id&score
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate
                .opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, lastId, offSet, 3);

        if (typedTuples.isEmpty() || typedTuples == null)
            return Result.ok();

        //解析获取blogId、minTime、offSet
        List<Blog> blogList = new ArrayList<>();    //保存blog
        Long minTime = lastId;   //最小时间戳
        Integer offset = 1;     //偏移量，默认为1
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            //获取blogId并保存blog信息
            Long blogId = Long.valueOf(typedTuple.getValue());
            blogList.add(getById(blogId));
            //更新最小时间戳，并且维护偏移量
            if (minTime == typedTuple.getScore().longValue())  //出现了同样score的内容，偏移量需增加
                offset++;
            else {  //出现了更小的score（即时间戳），维护minTime，偏移量复位
                minTime = typedTuple.getScore().longValue();
                offset = 1;
            }
        }
        for (Blog blog : blogList) {
            queryBlogUser(blog);
            isBlogLiked(blog);
        }

        //封装并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogList);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(offset);

        return Result.ok(scrollResult);
    }


    /**
     * 查询当前用户是否点赞博客，将isLike字段进行赋值
     * @return
     */
    private void isBlogLiked(Blog blog){
        UserDTO user = UserHolder.getUser();

        //若用户未登录则直接返回
        if (user == null)
            return;

        Long userId = user.getId();
        //用户已经登录
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();

        Double score = redisTemplate.opsForZSet().score(key, userId.toString());

        if (score != null)  //若能查到
            blog.setIsLike(true);
        else
            blog.setIsLike(false);
    }
}
